﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using Newtonsoft.Json;




namespace MapTool
{
    public class GlobalFun
    {

        /// <summary>
        /// 通过二进制序列化的方式对对象进行深度复制
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepCopyByBinary<T>(T obj)
        {
            object retval;
            try
            {
                using MemoryStream ms = new();
                BinaryFormatter bf = new();
                bf.Binder = new UBinder();

                bf.Serialize(ms, obj);

                ms.Seek(0, SeekOrigin.Begin);
                retval = bf.Deserialize(ms);

                ms.Close();
            }
            catch (Exception ex)
            {
        
                throw;
            }

            return (T)retval;
        }


        /// <summary>
        /// 加载Map
        /// </summary>
        /// <param name="productName"></param>
        public static void LoadMap(string productName)
        {
            string filePath = Path.Combine(GlobalData.ProductPath, productName, "Map");
            if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); }
            //遍历产品名文件夹的以.json结尾的文件
            foreach (var fileItem in Directory.GetFiles(filePath))
            {
                if (fileItem is null)
                {
                    
                    break;
                }
                if (fileItem.Contains(".json"))
                {
                    var map = GlobalFun.GetJsonFile<MapWafer>(fileItem);
                    if (map != null)
                    {
                        Application.Current.Dispatcher.Invoke(() => { GlobalData.Instance.Map = map; });
                    }
                }
            }
        }


        /// <summary>
        /// 保存Map
        /// </summary>
        /// <param name="productName"></param>
        public static void SaveMap(string productName)
        {
            string filePath = Path.Combine(GlobalData.ProductPath, productName, "Map");
            if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); }
            string backupPath = Path.Combine(filePath, "Backup");
            if (!Directory.Exists(backupPath)) { Directory.CreateDirectory(backupPath); }
            //先执行剪切备份操作
            //foreach (var file in Directory.EnumerateFiles(filePath))
            //{
            //    File.Move(file, Path.Combine(backupPath, Path.GetFileName(file)), true);
            //}
            if (GlobalData.Instance.Map != null)
            {
                string savePath = Path.Combine(filePath, $"Map.json");
                GlobalFun.SaveJsonFile<MapWafer>(savePath, GlobalData.Instance.Map);
            }
        }


        /// <summary>
        /// 将对象保存为json文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="savePath"></param>
        /// <param name="obj"></param>
        public static void SaveJsonFile<T>(string savePath, T obj, bool isCopy = true)
        {
            //string copy = string.Empty;
            try
            {
                //if (File.Exists(savePath) && isCopy)
                //{
                //    copy = Path.Combine(Path.GetDirectoryName(savePath)!, Path.GetFileNameWithoutExtension(savePath) + "backup.json");
                //    File.Move(savePath, copy, true);

                //}
                using StreamWriter fs = new(savePath, false);
                JsonSerializer jsonSerializer = new()
                {
                    Formatting = Formatting.Indented,
                    TypeNameHandling = TypeNameHandling.All,
                    PreserveReferencesHandling = PreserveReferencesHandling.All,
                    ObjectCreationHandling = ObjectCreationHandling.Replace,
                };
                jsonSerializer.Serialize(fs, obj);

                //if (!string.IsNullOrEmpty(copy) && System.IO.File.Exists(copy))
                //{
                //    System.IO.File.Delete(copy);
                //}
            }
            catch (Exception ex)
            {
  
            }
        }

        public static T? GetJsonFile<T>(string filePath)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    using FileStream fs = new(filePath, FileMode.Open, FileAccess.Read);
                    TextReader textReader = new StreamReader(fs);
                    JsonReader jsonReader = new JsonTextReader(textReader);
                    JsonSerializer jsonSerializer = new()
                    {
                        Formatting = Formatting.Indented,
                        TypeNameHandling = TypeNameHandling.All,
                        PreserveReferencesHandling = PreserveReferencesHandling.All,
                        ObjectCreationHandling = ObjectCreationHandling.Replace,
                    };
                    return jsonSerializer.Deserialize<T>(jsonReader);
                }
                catch (Exception ex)
                {
                  
                    return default;
                }
            }
            else
                return default;
        }

 

    }
    public class UBinder : SerializationBinder
    {
        public override Type? BindToType(string assemblyName, string typeName)
        {
            Type? type = null;
            Assembly ass;
            ass = Assembly.GetExecutingAssembly();
            type = ass.GetType(typeName);

            if (type == null)
            {
                var assbs = AppDomain.CurrentDomain.GetAssemblies();
                var asses = assbs.Where((a) => a.FullName == assemblyName);
                if (asses is null) return type;
                if (asses.Any())
                {
                    return asses.First().GetType(typeName);
                }
            }

            return type;
        }
    }
}
